package be.djdb.manipulators.streams.util;

import java.util.logging.Level;
import java.util.logging.Logger;


public class StringtagFinder {
	private char tagbuffer[];//buffer om match te schrijven
	private char actifchar;
	private String tofind;//img:=>>>>>img:<<<<<img/img.gif
	private int reclength;//4=>>>>>img:<<<<<img/img.gif
	private int recklok;//actieve plaats van char recorder
	private boolean tagenabled;
	private boolean match;
	private static final boolean DEBUG = false;
	private char firstchar;//voor sneller te kunnen zoeken
	public StringtagFinder(String tofind) {
		this.tofind = tofind;
		firstchar = tofind.charAt(0);
		reclength = tofind.length();
		SetReset();
	}
	public boolean tagfinder(int charint){
		actifchar = (char)charint;
		/*if(!getenabled()){//merker negatieve flank
			SetReset();
		}*/
		char x = tofind.charAt(recklok);// eerste letter setten
			if(recklok +1 < reclength && x== actifchar){//(dutch)Mogelijk gevonden voorlopig positieve match v/d tag
				if (DEBUG){log(Level.WARNING, "from"+tofind+"find"+ actifchar); }
				setenabled(true);
	    		tagbuffer[recklok]=(char)charint;
	    		if (DEBUG){log(Level.WARNING, "buffer"+ new String(tagbuffer)); }
	    		recklok++;
	    		return true;//op naar de volgende letter
	    	}else if(getenabled()){//mogelijk positieve match
				setenabled(false);
				if (DEBUG){log(Level.WARNING, "buffer"+ new String(tagbuffer)); }
				if((char)charint== actifchar&& recklok +1 == reclength){//volledige positieve match gevonden tijd om er iets mee te doen
		    		tagbuffer[recklok]=(char)charint;
		    		match = true;
					return true;
				}
	    		return false;//deels positieve match  dus herbeginnen
	    		//*************************************
	    	}else{
	    		return false;
	    	}
	   }
	public void SetReset(){
		tagbuffer= new char[reclength];
		recklok = 0;//initializeren
		match = false;
	}
	private  void setenabled(boolean enabled){
		this.tagenabled = enabled;
	}
	private boolean getenabled(){
	  return this.tagenabled;
	}
	public boolean ismatchfound(){
		return match;
	}
	public String getbuffer(){
		return new String(trimarray(tagbuffer,recklok));
	}
	private char[]trimarray(char[]array,int length){
		char buffer[] = new char[length];
		System.arraycopy(array, 0, buffer, 0, length);//arraycopy(Object srcarray, int srcPos,Object destarray,int destPos,int length)
		return buffer;
	}
    private static  void log(Level level, String msg ){
        String tag ="<>>>>*UpdateCV-L Roegiers 80072631156*<<<<>";
        Logger.getLogger(StringtagFinder.class.getName()).log(level, tag + msg);
    }
}
